<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <title>分类管理 - 个人博客</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #0a1929;
            color: #e0e0e0;

            font-family: 'Roboto', sans-serif;
        }

        .container {
            max-width: 1200px;
        }

        .form-label {
            color: #e0e0e0;
        }

        .page-header {
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 15px;
            border-bottom: 1px solid #1e3a5f;
        }

        .card {
            background-color: #132f4c;
            border: none;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
        }

        .card-header {
            background-color: #173a5e;
            color: #66b2ff;
            font-weight: bold;
            border-bottom: 1px solid #1e3a5f;
            border-radius: 12px 12px 0 0 !important;
        }

        .table {
            color: #e0e0e0;
        }

        .table thead th {
            border-bottom: 2px solid #1e3a5f;
            color: #66b2ff;
        }

        .table td, .table th {
            border-top: 1px solid #1e3a5f;
            vertical-align: middle;
        }

        .btn-primary {
            background-color: #0059b2;
            border-color: #0059b2;
        }

        .btn-primary:hover {
            background-color: #0069d9;
            border-color: #0062cc;
        }

        .btn-danger {
            background-color: #d32f2f;
            border-color: #d32f2f;
        }

        .btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
        }

        .form-control, .form-select {
            background-color: #0a1929;
            border: 1px solid #1e3a5f;
            color: #e0e0e0;
        }

        .form-control:focus, .form-select:focus {
            background-color: #0a1929;
            border-color: #66b2ff;
            box-shadow: 0 0 0 0.25rem rgba(102, 178, 255, 0.25);
            color: #e0e0e0;
        }

        .alert-success {
            background-color: #081c15;
            color: #95d5b2;
            border-color: #081c15;
        }

        .alert-danger {
            background-color: #370617;
            color: #f48c8c;
            border-color: #370617;
        }

        .icon-cell {
            font-size: 1.5rem;
            text-align: center;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<!-- 导航栏替换为统一片段 -->
<div th:replace="~{fragments/navbar :: navbar}"></div>

<div class="container">
    <!-- 页面标题 -->
    <div class="page-header">
        <h2><i class="bi bi-tags"></i> 分类管理</h2>
    </div>

    <!-- 提示消息 -->
    <div th:if="${message}" class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill"></i> <span th:text="${message}"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <div th:if="${error}" class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i> <span th:text="${error}"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>

    <div class="row">
        <!-- 分类表单 -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-plus-circle"></i>
                    <span th:if="${category.id == null}">添加分类</span>
                    <span th:unless="${category.id == null}">编辑分类</span>
                </div>
                <div class="card-body">
                    <form th:action="${category.id == null ? '/admin/categories' : '/admin/categories/' + category.id}"
                          method="post" th:object="${category}">
                        <div class="mb-3">
                            <label for="name" class="form-label">分类名称</label>
                            <input type="text" class="form-control" id="name" name="name" th:field="*{name}" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">分类描述</label>
                            <textarea class="form-control" id="description" name="description" th:field="*{description}"
                                      rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="icon" class="form-label">图标 (Bootstrap Icons 类名)</label>
                            <div class="input-group">
                                <span class="input-group-text">bi-</span>
                                <input type="text" class="form-control" id="icon" name="icon" th:field="*{icon}"
                                       placeholder="tag">
                            </div>
                            <div class="form-text">例如：输入 "code-slash" 将显示为 <i class="bi bi-code-slash"></i>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="displayOrder" class="form-label">显示顺序</label>
                            <input type="number" class="form-control" id="displayOrder" name="displayOrder"
                                   th:field="*{displayOrder}" value="0">
                        </div>
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i>
                                <span th:if="${category.id == null}">添加分类</span>
                                <span th:unless="${category.id == null}">更新分类</span>
                            </button>
                            <a th:if="${category.id != null}" href="/admin/categories"
                               class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle"></i> 取消编辑
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 分类列表 -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <i class="bi bi-list-ul"></i> 分类列表
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary" id="sortModeBtn">
                            <i class="bi bi-sort-numeric-down"></i> 排序模式
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div th:if="${#lists.isEmpty(categories)}" class="text-center p-4">
                        <i class="bi bi-emoji-frown" style="font-size: 2rem;"></i>
                        <p class="mt-2">暂无分类，请添加</p>
                    </div>
                    <div th:unless="${#lists.isEmpty(categories)}" class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>图标</th>
                                <th>名称</th>
                                <th>描述</th>
                                <th>顺序</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="cat : ${categories}">
                                <td th:text="${cat.id}"></td>
                                <td class="icon-cell">
                                    <i class="bi"
                                       th:classappend="${cat.icon != null ? 'bi-' + cat.icon : 'bi-tag'}"></i>
                                </td>
                                <td th:text="${cat.name}"></td>
                                <td th:text="${cat.description}"></td>
                                <td th:text="${cat.displayOrder}"></td>
                                <td>
                                    <div class="d-flex gap-2">
                                        <a th:href="@{/admin/categories/{id}/edit(id=${cat.id})}"
                                           class="btn btn-sm btn-primary">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <form th:action="@{/admin/categories/{id}/delete(id=${cat.id})}" method="post"
                                              onsubmit="return confirm('确定要删除这个分类吗？')">
                                            <button type="submit" class="btn btn-sm btn-danger">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
<script>
    // 分类排序功能
    document.addEventListener('DOMContentLoaded', function () {
        const sortModeBtn = document.getElementById('sortModeBtn');
        const categoryTable = document.querySelector('.table tbody');
        let sortable = null;
        let sortMode = false;

        if (sortModeBtn && categoryTable) {
            sortModeBtn.addEventListener('click', function () {
                sortMode = !sortMode;

                if (sortMode) {
                    // 启用排序模式
                    sortModeBtn.innerHTML = '<i class="bi bi-check-circle"></i> 保存排序';
                    sortModeBtn.classList.remove('btn-outline-primary');
                    sortModeBtn.classList.add('btn-success');

                    // 初始化拖拽排序
                    sortable = new Sortable(categoryTable, {
                        animation: 150,
                        handle: '.icon-cell',
                        ghostClass: 'bg-light'
                    });

                    // 添加提示信息
                    const rows = categoryTable.querySelectorAll('tr');
                    rows.forEach(row => {
                        const iconCell = row.querySelector('.icon-cell');
                        if (iconCell) {
                            iconCell.style.cursor = 'grab';
                            iconCell.setAttribute('title', '拖拽排序');
                        }
                    });
                } else {
                    // 保存排序
                    sortModeBtn.innerHTML = '<i class="bi bi-sort-numeric-down"></i> 排序模式';
                    sortModeBtn.classList.remove('btn-success');
                    sortModeBtn.classList.add('btn-outline-primary');

                    // 获取新的排序顺序
                    const rows = categoryTable.querySelectorAll('tr');
                    const categoryIds = [];

                    rows.forEach((row, index) => {
                        const categoryId = row.querySelector('td:first-child').textContent;
                        categoryIds.push(parseInt(categoryId));

                        // 更新显示的顺序值
                        const orderCell = row.querySelector('td:nth-child(5)');
                        if (orderCell) {
                            orderCell.textContent = index;
                        }
                    });

                    // 发送排序数据到服务器
                    const token = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                    const header = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

                    fetch('/admin/categories/reorder', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            [header]: token
                        },
                        body: JSON.stringify(categoryIds)
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // 显示成功消息
                                const alertDiv = document.createElement('div');
                                alertDiv.className = 'alert alert-success alert-dismissible fade show';
                                alertDiv.innerHTML = `
                                    <i class="bi bi-check-circle-fill"></i> 分类排序已更新
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                `;
                                document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.row'));
                            }
                        })
                        .catch(error => {
                            console.error('Error saving category order:', error);
                        });

                    // 销毁排序实例
                    if (sortable) {
                        sortable.destroy();
                        sortable = null;
                    }

                    // 恢复图标样式
                    const iconCells = categoryTable.querySelectorAll('.icon-cell');
                    iconCells.forEach(cell => {
                        cell.style.cursor = 'default';
                        cell.removeAttribute('title');
                    });
                }
            });
        }
    });
</script>

<!-- Bootstrap 组件初始化已由 turbo-fixes.js 统一管理 -->
</body>
</html>